﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using NHibernateDB;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using MigraDoc.DocumentObjectModel.Shapes;

namespace MedicalDB.Export
{
    public class ExportPDF
    {
        private string limba;
        private string fileName;
        private string CNP;
        private List<string> Deleteimages = new List<string>();

        public ExportPDF(string limba, string fileName, string CNP)
        {
            this.limba = limba;
            this.fileName = fileName;
            this.CNP = CNP;
        }

        public Boolean Generare()
        {
            PDFGenerator pdfgen = new PDFGenerator();

            //create new pdf document
            Document document = new Document();
 
            document.Info.Title = "ASISTSYS";

            pdfgen.DefineStyles(document);

            document.DefaultPageSetup.Orientation = Orientation.Landscape;
            
            Section section = document.AddSection();

            string[] headerdgp = new string[12];
            
            string xmlFile = @"C:\Language" + limba + ".xml";
            XMLParser xmlParser = new XMLParser(xmlFile);

            List<string> namesForm = xmlParser.ExtractAttribute("lvDateGenerale", string.Empty, string.Empty, "name");
            List<string> titles = xmlParser.ExtractAttribute("VizualizareDate", string.Empty, string.Empty, "formula");
            Dictionary<string, string> pdfs = xmlParser.ExtractAttributePairs("pdfGenerator", string.Empty, string.Empty, "name", "formula");

            
            int valuetitles = 0;

            int value = 0;

            foreach (string s in namesForm)
                headerdgp[value] = namesForm[value++];
                      
            PersistenceManager pm = PersistenceManager.Instance;
            IList<DateGeneralePacient> lista = pm.RetrieveEquals<DateGeneralePacient>("IdPacient", CNP);
            string[,] datedgp = new string[lista.Count, 12];
            int row = 0;
            string nume=string.Empty;
            string prenume=string.Empty;

            value = 0;
            foreach (DateGeneralePacient dgp in lista)
            {
                value = 0;
                datedgp[row, value++] = dgp.IdPacient;
                datedgp[row, value++] = dgp.Nume;
                nume = dgp.Nume;
                datedgp[row, value++] = dgp.Prenume;
                prenume = dgp.Prenume;
                datedgp[row, value++] = dgp.Sex;
                datedgp[row, value++] = dgp.DataNasterii.ToString();
                datedgp[row, value++] = dgp.LoculNasterii;
                datedgp[row, value++] = dgp.Resedinta;
                datedgp[row, value++] = dgp.DomiciliuLegal;
                datedgp[row, value++] = dgp.GrupaSanguina;
                datedgp[row, value++] = dgp.Ocupatie;
                datedgp[row, value++] = dgp.LocMunca;
                datedgp[row, value++] = dgp.TalonPensie;
                row++;
            }
            pdfgen.AddTitle(document, "ASISTSYS", 10);
            pdfgen.AddText2(document, pdfs["Introduction"],  5,true);
            pdfgen.AddText2(document, pdfs["Nume"] + nume,  2,false);
            pdfgen.AddText2(document, pdfs["Prenume"] + prenume, 2,false);
            pdfgen.AddText2(document, pdfs["Data"]+ DateTime.Now.ToString(), 2,false);


            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headerdgp, datedgp, row);


            //Evaluare Sisteme

            string [] headeres = new string[13];
            value = 0;
            namesForm = xmlParser.ExtractAttribute("lvEvaluareSisteme", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headeres[value] = namesForm[value++];

            IList<EvaluareSisteme> lista2 = pm.RetrieveEquals<EvaluareSisteme>("IdPacient", CNP);
            string[,] datees = new string[lista2.Count,13];
            row=0;
            value = 0;
            foreach (EvaluareSisteme es in lista2)
            {
                value = 0;
                datees[row, value++] = es.DataEvaluari.ToString();
                datees[row, value++] = es.TegumenteMucoase;
                datees[row, value++] = es.SistemCelularSubcutanat;
                datees[row, value++] = es.SistemGanglionar;
                datees[row, value++] = es.SistemOsteoarticular;
                datees[row, value++] = es.SistemCardiovascular;
                datees[row, value++] = es.SistemRespirator;
                datees[row, value++] = es.SistemDigestiv;
                datees[row, value++] = es.SistemGenitoUrinar;
                datees[row, value++] = es.Snc;
                datees[row, value++] = es.ExaminareParacilinica;
                datees[row, value++] = es.Recomandari;
                datees[row, value++] = es.Concluzii;
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headeres, datees, row);



            //Evaluare Sociala
            string[] headereso = new string[4];
            value = 0;
            namesForm = xmlParser.ExtractAttribute("lvEvaluareSociala", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headereso[value] = namesForm[value++];
            

            IList<EvaluareSociala> lista3 = pm.RetrieveEquals<EvaluareSociala>("IdPacient", CNP);
            
            
            string[,] dateeso = new string[lista3.Count, 4];
            row = 0;
            value = 0;
            foreach (EvaluareSociala es in lista3)
            {
                value = 0;
                dateeso[row, value++] = es.DataEvaluari.ToString();
                dateeso[row, value++] = es.RezultateSociale;
                dateeso[row, value++] = es.RezultateAbilitati;
                dateeso[row, value++] = es.ConcluziiAsistent;                
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headereso, dateeso, row);



            //Examen Oncologic
            string[] headereo = new string[8];
            value = 0;
            namesForm = xmlParser.ExtractAttribute("lvExamenOncologic", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headereo[value] = namesForm[value++];

            IList<ExamenOncologic> lista4 = pm.RetrieveEquals<ExamenOncologic>("IdPacient", CNP);


            string[,] dateeo = new string[lista4.Count, 8];
            row = 0;
            value = 0;
            foreach (ExamenOncologic eo in lista4)
            {
                value = 0;
                dateeo[row, value++] = eo.CavitateBucala;
                dateeo[row, value++] = eo.Tegumente;
                dateeo[row, value++] = eo.GrupeGangiPalpabile;
                dateeo[row, value++] = eo.San;
                dateeo[row, value++] = eo.OrgGenFem;
                dateeo[row, value++] = eo.CitSecrVaginale;
                dateeo[row, value++] = eo.ProstataRect;
                dateeo[row, value++] = eo.Altele;
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headereo, dateeo, row);

                       
            
            //Fisa Externare
            string[] headerfe = new string[15];
            value = 0;
            namesForm = xmlParser.ExtractAttribute("lvFisaExternare", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headerfe[value] = namesForm[value++];

            IList<FisaExternare> lista5 = pm.RetrieveEquals<FisaExternare>("IdPacient", CNP);

            string[,] datefe = new string[lista5.Count, 15];
            row = 0;
            value = 0;
            foreach (FisaExternare fe in lista5)
            {
                value = 0;
                datefe[row, value++] = fe.Data.ToString();
                datefe[row, value++] = fe.Vindecat.ToString();
                datefe[row, value++] = fe.Ameliorat.ToString();
                datefe[row, value++] = fe.Transferat.ToString();
                datefe[row, value++] = fe.Agravat.ToString();
                datefe[row, value++] = fe.Decedat.ToString();
                datefe[row, value++] = fe.MotivDeces;
                datefe[row, value++] = fe.AlteStari;
                datefe[row, value++] = fe.DiagnosticExternare;
                datefe[row, value++] = fe.RecomandariEpicriza;
                datefe[row, value++] = fe.PerioadaInternarii;
                datefe[row, value++] = fe.Concediu;
                datefe[row, value++] = fe.Control;
                datefe[row, value++] = fe.Tratament;
                datefe[row, value++] = fe.Semnatura;
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headerfe, datefe, row);


            //Fisa Internare

            string[] headerfi = new string[10];
            value = 0;
            namesForm = xmlParser.ExtractAttribute("lvFisaInternare", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headerfi[value] = namesForm[value++];

            IList<FiseInternare> lista6 = pm.RetrieveEquals<FiseInternare>("IdPacient", CNP);

            string[,] datefi = new string[lista6.Count, 10];
            row = 0;
            value = 0;
            foreach (FiseInternare fi in lista6)
            {
                value = 0;

                datefi[row, value++] = fi.DataInternarii.ToString();
                datefi[row, value++] = fi.DiagnosticInternare;
                datefi[row, value++] = fi.Diagnostic72h;
                datefi[row, value++] = fi.DiagnosticTrimitere;
                datefi[row, value++] = fi.MotiveleInternarii;
                datefi[row, value++] = fi.DiagnosticPrincipal;
                datefi[row, value++] = fi.BoliConcomitente;
                datefi[row, value++] = fi.InternatUrgenta;
                datefi[row, value++] = fi.Sectia;                
                datefi[row, value++] = fi.Salon;
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headerfi, datefi, row);


            //FunctiiVitale
            string[] headerfv = new string[8];
            value = 0;

            namesForm = xmlParser.ExtractAttribute("lvFunctiiVitale", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headerfv[value] = namesForm[value++];

            IList<FunctiiVitale> lista7 = pm.RetrieveEquals<FunctiiVitale>("IdPacient", CNP);

            string[,] datefv = new string[lista7.Count, 8];
            row = 0;
            value = 0;
            foreach (FunctiiVitale fv in lista7)
            {
                value = 0;

                datefv[row, value++] = fv.DataEvaluarii.ToString();
                datefv[row, value++] = fv.Greutate.ToString();
                datefv[row, value++] = fv.TensiuneArteriala.ToString();
                datefv[row, value++] = fv.Puls.ToString();
                datefv[row, value++] = fv.FrecventaRespiratorie.ToString();
                datefv[row, value++] = fv.Apetit;
                datefv[row, value++] = fv.Diureza;
                datefv[row, value++] = fv.ConcluziiAsistent;             
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headerfv, datefv, row);


            //GraficADS
            string[] headerga = new string[7];
            value = 0;

            namesForm = xmlParser.ExtractAttribute("lvGraficADS", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headerga[value] = namesForm[value++];

            IList<GraficADS> lista8 = pm.RetrieveEquals<GraficADS>("IdPacient", CNP);

            string[,] datega = new string[lista8.Count, 7];
            row = 0;
            value = 0;
            foreach (GraficADS fv in lista8)
            {
                value = 0;

                datega[row, value++] = fv.Data.ToString();
                datega[row, value++] = fv.MicDejun;
                datega[row, value++] = fv.Pranz;
                datega[row, value++] = fv.Cina;
                datega[row, value++] = fv.Diureza;
                datega[row, value++] = fv.Scaun;
                datega[row, value++] = fv.SemnaturaInfirmiera;
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headerga, datega, row);


            //Igiena
            string[] headerig = new string[5];
            value = 0;

            namesForm = xmlParser.ExtractAttribute("lvIgiena", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headerig[value] = namesForm[value++];

            IList<Igiena> lista9 = pm.RetrieveEquals<Igiena>("IdPacient", CNP);

            string[,] dateig = new string[lista9.Count, 5];
            row = 0;
            value = 0;
            foreach (Igiena ig in lista9)
            {
                value = 0;

                dateig[row, value++] = ig.Data.ToString();
                dateig[row, value++] = ig.SpalatMainiFata.ToString();
                dateig[row, value++] = ig.Piepatanat.ToString();
                dateig[row, value++] = ig.Barbierit.ToString();
                dateig[row, value++] = ig.ServitMasa.ToString();
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headerig, dateig, row);


            //Imbracat
            string[] headerim = new string[6];
            value = 0;

            namesForm = xmlParser.ExtractAttribute("lvImbracat", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headerim[value] = namesForm[value++];

            IList<Imbracat> lista10 = pm.RetrieveEquals<Imbracat>("IdPacient", CNP);

            string[,] dateim = new string[lista10.Count, 6];
            row = 0;
            value = 0;
            foreach (Imbracat im in lista10)
            {
                value = 0;

                dateim[row, value++] = im.Data.ToString();
                dateim[row, value++] = im.ImbracatSingur.ToString();
                dateim[row, value++] = im.HainePuneScoate.ToString();
                dateim[row, value++] = im.CamasaPuneScoate.ToString();
                dateim[row, value++] = im.LegatSireturi.ToString();
                dateim[row, value++] = im.IncheieDescheieNasturi.ToString();
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headerim, dateim, row);


            //Interventie Chirurgicala
            string[] headeric = new string[4];
            value = 0;

            namesForm = xmlParser.ExtractAttribute("lvInterventieChirurgicala", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headeric[value] = namesForm[value++];

            IList<InterventieChirurgicala> lista11 = pm.RetrieveEquals<InterventieChirurgicala>("IdPacient", CNP);

            string[,] dateic = new string[lista11.Count, 4];
            row = 0;
            value = 0;
            foreach (InterventieChirurgicala ic in lista11)
            {
                value = 0;

                dateic[row, value++] = ic.Data.ToString();
                dateic[row, value++] = ic.Tehnica;
                dateic[row, value++] = ic.Boala;
                dateic[row, value++] = ic.Semnatura;
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headeric, dateic, row);


            //Invesigatii
            string[] headerin = new string[7];
            value = 0;

            namesForm = xmlParser.ExtractAttribute("lvInvestigatii", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headerin[value] = namesForm[value++];

            IList<Investigatii> lista12 = pm.RetrieveEquals<Investigatii>("IdPacient", CNP);

            string[,] datein = new string[lista12.Count, 7];
            row = 0;
            value = 0;
            foreach (Investigatii inv in lista12)
            {
                value = 0;

                datein[row, value++] = inv.Data.ToString();
                datein[row, value++] = inv.InvestigatiLaborator;
                datein[row, value++] = inv.ExaminariRadiologice;
                datein[row, value++] = inv.ExamemeSpecialitate;
                datein[row, value++] = inv.DiagAnatoPatologice;
                datein[row, value++] = inv.IstoricBoala;
                datein[row, value++] = inv.ExamenClinicMedical;
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headerin, datein, row);



            //Medicatii
            string[] headerme = new string[10];
            value = 0;

            namesForm = xmlParser.ExtractAttribute("lvMedicatii", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headerme[value] = namesForm[value++];

            IList<Medicatii> lista13 = pm.RetrieveEquals<Medicatii>("IdPacient", CNP);

            string[,] dateme = new string[lista13.Count, 10];
            row = 0;
            value = 0;
            foreach (Medicatii med in lista13)
            {
                value = 0;

                dateme[row, value++] = med.DataUrgentei.ToString();
                dateme[row, value++] = med.Urgenta;
                dateme[row, value++] = med.DataContributii.ToString();
                dateme[row, value++] = med.Contributii;
                dateme[row, value++] = med.DataDonatii.ToString();
                dateme[row, value++] = med.Donatii;
                dateme[row, value++] = med.DataMedicatie.ToString();
                dateme[row, value++] = med.MedicatieCompensate;
                dateme[row, value++] = med.DataMaterialeSanitare.ToString();
                dateme[row, value++] = med.MaterialeSanitare;
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headerme, dateme, row);


            //Persoana Trimitere
            string[] headerpt = new string[2];
            value = 0;

            namesForm = xmlParser.ExtractAttribute("lvPersoanaTrimitere", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headerpt[value] = namesForm[value++];
            
            IList<PersoanaTrimitere> lista14 = pm.RetrieveEquals<PersoanaTrimitere>("IdPacient", CNP);

            string[,] datept = new string[lista14.Count, 2];
            row = 0;
            value = 0;
            foreach (PersoanaTrimitere pt in lista14)
            {
                value = 0;

                datept[row, value++] = pt.Nume;
                datept[row, value++] = pt.Telefon;
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headerpt, datept, row);


            //Persoana Contact
            string[] headerpc = new string[3];
            value = 0;

            namesForm = xmlParser.ExtractAttribute("lvPersoanaContact", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headerpc[value] = namesForm[value++];

            IList<PersoaneContact> lista15 = pm.RetrieveEquals<PersoaneContact>("IdPacient", CNP);

            string[,] datepc = new string[lista15.Count, 3];
            row = 0;
            value = 0;
            foreach (PersoaneContact pc in lista15)
            {
                value = 0;

                datepc[row, value++] = pc.Nume;
                datepc[row, value++] = pc.Domiciliu;
                datepc[row, value++] = pc.Telefon;
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headerpc, datepc, row);



            //Utilitati
            string[] headerut = new string[4];
            value = 0;

            namesForm = xmlParser.ExtractAttribute("lvUtilitati", string.Empty, string.Empty, "name");

            foreach (string s in namesForm)
                headerut[value] = namesForm[value++];

            IList<Utilitati> lista16 = pm.RetrieveEquals<Utilitati>("IdPacient", CNP);

            string[,] dateut = new string[lista16.Count, 4];
            row = 0;
            value = 0;
            foreach (Utilitati ut in lista16)
            {
                value = 0;
                dateut[row, value++] = ut.Data.ToString();
                dateut[row, value++] = ut.InchisDeschisSertare.ToString();
                dateut[row, value++] = ut.ManevrareTvRadio.ToString();
                dateut[row, value++] = ut.InchisDeschisUsaFereastra.ToString();
                row++;
            }

            pdfgen.AddTablesMultipleLines(document, titles[valuetitles++], new string[0, 0], 0, headerut, dateut, row);




            //Generare imagine
            Dictionary<int,string> senzorNume = new Dictionary<int,string>();
            pm = PersistenceManager.Instance;
            IList<Senzori> listSenzori = pm.RetrieveAll<Senzori>(SessionAction.BeginAndEnd);

            foreach (Senzori s in listSenzori)
            {               
                senzorNume.Add(s.IdSenzor, s.NumeSenzor);
            }

            
            pm = PersistenceManager.Instance;
            IList<InvestigatiiSenzor> invSenzor = pm.RetrieveEquals<InvestigatiiSenzor>("IdPacient", CNP);
           
            foreach (InvestigatiiSenzor invsz in invSenzor)
            {
                if (senzorNume[invsz.IdSenzor].Contains("Temperatura"))
                {
                    GraficTemperatura gtem = new GraficTemperatura(invsz.DataInceput, invsz.DataSfarsit, invsz.IdSenzor, invsz.IdPacient,limba);
                    //Salvare Imagine
                    gtem.CreateGraph();
                    string Image = gtem.SaveImage();

                    //Add image
                    Section section2 = document.LastSection;
                    section2.AddPageBreak();
                    Paragraph paragraph = section.AddParagraph(pdfs["Temperatura"], "Heading2");

                    MigraDoc.DocumentObjectModel.Shapes.Image image = section2.AddImage(Image);

                    image.LockAspectRatio = true;
                    image.Left = ShapePosition.Center;

                    Deleteimages.Add(Image);
                        
                }

                if (senzorNume[invsz.IdSenzor].Contains("Lumina"))
                {
                    GraficLumina glum = new GraficLumina(invsz.DataInceput, invsz.DataSfarsit, invsz.IdSenzor, invsz.IdPacient,limba);
                    //Salvare Imagine
                    glum.CreateGraph();
                    string Image = glum.SaveImage();

                    //Add image
                    Section section2 = document.LastSection;
                    section2.AddPageBreak();
                    Paragraph paragraph = section.AddParagraph(pdfs["Lumina"], "Heading2");
                    MigraDoc.DocumentObjectModel.Shapes.Image image = section2.AddImage(Image);
                    image.LockAspectRatio = true;
                    image.Left = ShapePosition.Center;
                    Deleteimages.Add(Image);
                }
                if (senzorNume[invsz.IdSenzor].Contains("ECG"))
                {
                    GraficECG gecg = new GraficECG(invsz.DataInceput, invsz.DataSfarsit, invsz.IdSenzor, invsz.IdPacient,limba);
                    //Salvare Imagine
                    gecg.CreateGraph();
                    gecg.CreateGraph2();
                    List<string> listImage = gecg.SaveImage();

                    //Add image
                    Section section2 = document.LastSection;
                    section2.AddPageBreak();
                    Paragraph paragraph = section.AddParagraph(pdfs["ECG"], "Heading2");
                    foreach (string Image in listImage)
                    {
                        MigraDoc.DocumentObjectModel.Shapes.Image image = section2.AddImage(Image);
                        image.LockAspectRatio = true;
                        image.Left = ShapePosition.Center;
                        Deleteimages.Add(Image);
                    }
                }
                if (senzorNume[invsz.IdSenzor].Contains("BP"))
                {
                    GraficBP gbp = new GraficBP(invsz.DataInceput, invsz.DataSfarsit, invsz.IdSenzor, invsz.IdPacient,limba);
                    //Salvare Imagine
                    gbp.CreateGraph();
                    gbp.CreateGraph2();
                    List<string> listImage = gbp.SaveImage();

                    //Add image
                    Section section2 = document.LastSection;
                    section2.AddPageBreak();
                    Paragraph paragraph = section.AddParagraph(pdfs["BP"], "Heading2");
                    foreach (string Image in listImage)
                    {
                        MigraDoc.DocumentObjectModel.Shapes.Image image =section2.AddImage(Image);
                        image.LockAspectRatio = true;
                        image.Left = ShapePosition.Center;
                        Deleteimages.Add(Image);
                    }
                }
            }           

            //Render Document
            MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToFile(document, "MigraDoc.mdddl");
            PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
            renderer.Document = document;
            renderer.RenderDocument();
            // Save the document...
            renderer.PdfDocument.Save(fileName);

            foreach( string Image in Deleteimages)
                System.IO.File.Delete(Image);

            return true;
        }

    }
}